import router from './router'
import store from './store'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = [ "/login", "/404" ]
router.beforeEach( async function ( to, from, next ) {
    Nprogress.start()
    if(store.getters.token) {
        // console.log(store.getters.token);
        if (to.path === "/login") {
            next("/")
        } else {
            if (!store.state.user.userInfo.userId) {
               const { roles } = await store.dispatch("user/getUserInfo");
               const routes = await store.dispatch("permission/filterRoutes", roles.menus);
               router.addRoutes(routes);
               router.addRoutes([...routes,{ path: '*', redirect: '/404', hidden: true }])
               next(to.path)
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) > -1) {
            next()
        } else {
            
            next("/login")
        }
    }
    Nprogress.done()
})

router.afterEach( function ( to, from ) {
    Nprogress.done()
})
